/*
 *  Copyright 2020-2025 the original author or authors.
 *  You cannot use this file unless authorized by the author.
 */

package org.ipig.commons.helper;

import java.util.zip.CRC32;

/**
 * 通用Hash算法
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id$$
 * @since 1.0
 */
public class HashAlgorithmsHelper {
    /**
     * CRC32算法
     *
     * @param msg 原始消息
     * @return 经过CRC32后的long值
     */
    public static long crc32(final String msg) {
        if (msg == null) {
            throw new RuntimeException("is null");
        }
        CRC32 crc32 = new CRC32();
        crc32.update(msg.getBytes());
        return crc32.getValue();
    }

    /**
     * FNV1_32_HASH算法
     *
     * @param msg 原始消息
     * @return 经过hash后的32位int值
     */
    public static int fnv1Hash32(String msg) {
        final int p = 16777619;
        int hash = (int) 2166136261L;
        for (int i = 0; i < msg.length(); i++) {
            hash = (hash ^ msg.charAt(i)) * p;
        }
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;
        return hash;
    }
}

